<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          style="margin-bottom: 10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          v-model="queryParams.keyword"
          @input="changeValue"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="deptTree"
          node-key="id"
          :data="depts"
          :props="defaultProps"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          @node-click="selectNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="space-between">
          <el-button size="mini" @click="sendMultiMessage">群发通知</el-button>
          <el-row>
            <el-button
              size="mini"
              type="primary"
              @click="$router.push('/employee/detail')"
              >添加员工</el-button
            >
            <el-button size="mini" @click="showExcelDialog = true"
              >excel导入</el-button
            >
            <el-button size="mini" @click="exportEmployeeExcel"
              >excel导出</el-button
            >
          </el-row>
        </el-row>
        <!-- 表格组件 -->
        <el-table
          ref="employeeTable"
          row-key="id"
          :data="employeeList"
          @select="selectChange"
          @select-all="selectChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template v-slot="{ row }">
              <el-avatar
                v-if="row.staffPhoto"
                :src="row.staffPhoto"
                :size="30"
              />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" sortable prop="mobile" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template v-slot="{ row }">
              {{ employmentMap[row.formOfEmployment] }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" width="280px">
            <template v-slot="{ row }">
              <el-button
                size="mini"
                type="text"
                @click="$router.push(`/employee/detail/${row.id}`)"
                >查看</el-button
              >
              <el-button size="mini" type="text" @click="btnRole(row.id)"
                >角色</el-button
              >
              <el-popconfirm
                title="确认删除该行数据吗？"
                @onConfirm="confirmDel(row.id)"
              >
                <el-button
                  slot="reference"
                  style="margin-left: 10px"
                  size="mini"
                  type="text"
                  >删除</el-button
                >
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev, pager, next"
            :total="total"
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            @current-change="changePage"
          />
        </el-row>
        <!-- 角色弹窗 -->
        <el-dialog :visible.sync="showRoleDialog" title="分配角色">
          <!-- 弹层内容 -->
          <!-- checkbox -->
          <el-checkbox-group v-model="roleIds">
            <!-- 放置n个的checkbox  要执行checkbox的存储值 item.id-->
            <el-checkbox
              v-for="item in roleList"
              :key="item.id"
              :label="item.id"
              >{{ item.name }}</el-checkbox
            >
          </el-checkbox-group>
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button type="primary" size="mini" @click="btnRoleOK"
                >确定</el-button
              >
              <el-button size="mini" @click="showRoleDialog = false"
                >取消</el-button
              >
            </el-col>
          </el-row>
        </el-dialog>
        <!-- 群发消息弹层 -->
        <el-dialog title="群发通知" :visible.sync="showMultiMessageDialog">
          <div class="select_users">
            <el-tag
              v-for="item in all_users"
              :key="item.id"
              closable
              @close="delSendUser(item)"
              >@{{ item.username }}</el-tag
            >
          </div>
          <el-form label-width="80px">
            <el-form-item label="消息等级">
              <el-select v-model="messageForm.type" size="mini">
                <el-option :value="1" label="通知消息" />
                <el-option :value="2" label="提示消息" />
                <el-option :value="3" label="重要消息" />
                <el-option :value="4" label="紧急消息" />
              </el-select>
            </el-form-item>
            <el-form-item label="通知内容">
              <el-input
                v-model="messageForm.content"
                type="textarea"
                :rows="4"
                place-holder="通知内容的长度在5-100个字符"
              />
            </el-form-item>
          </el-form>
          <!-- 群发通知 -->
          <template #footer>
            <el-row type="flex" justify="end">
              <el-button size="mini" @click="btnCancelSend">取消</el-button>
              <el-button size="mini" type="primary" @click="btnSendMultiMessage"
                >发送通知</el-button
              >
            </el-row>
          </template>
        </el-dialog>
      </div>
    </div>
    <!-- 导入excel组件 -->
    <import-excel
      :show-excel-dialog.sync="showExcelDialog"
      @uploadSuccess="getEmployeeList"
    />
  </div>
</template>
  
<script>
// 导入获取组织架构
import { getDepartment } from "@/api/department";
// 导入树形结构转化方法
import { transListToTreeData } from "@/utils/index";
// 导入文件保存
import FileSaver from "file-saver";
// 导入员工的api
import {
  getEmployeeList,
  exportEmployeeExcel,
  deleteEmployee,
  getEnableRoleList,
  getEmployeeDetail,
  assignRole,
  sendMessage,
} from "@/api/employee";
// 导入excel组件封装
import ImportExcel from "./components/import-excel.vue";

export default {
  name: "Employee",
  data() {
    return {
      showMultiMessageDialog: false, // 用来控制群发弹层的显示
      currentUserId: null, // 用来记录当前点击的用户id
      showRoleDialog: false, // 用来控制角色弹层的显示
      roleList: [], // 接收角色列表
      roleIds: [], // 用来双向绑定数据的
      employeeList: [], // 员工列表
      depts: [], // 组织数据
      showExcelDialog: false, // 是否显示excel导入弹窗
      // 树形组件配置
      defaultProps: {
        label: "name",
        children: "children",
      },
      // 查询参数
      queryParams: {
        departmentId: null,
        page: 1, // 当前页码
        pagesize: 10, // 每页条数
        keyword: "", // 模糊搜索字段
      },
      total: 0, // 记录员工的总数
      // 聘用形式
      employmentMap: {
        1: "正式",
        2: "非正式",
      },
      timer: null, // 防抖定时器
      selectUsers: [], // 已选择的员工列表
      // 群发消息等级
      messageForm: {
        type: 1, // 1 通知消息 2 提示消息 3  重要消息 4 紧急消息
        content: "",
      },
    };
  },
  // 注册excel组件
  components: {
    ImportExcel,
  },
  // 计算属性
  computed: {
    all_users() {
      return [...Object.values(this.selectUsers).flat()];
    },
  },
  created() {
    this.getDepartment();
  },
  methods: {
    // 获取组织架构
    async getDepartment() {
      // 递归方法 将列表转化成树形
      this.depts = transListToTreeData(await getDepartment(), 0);
      this.queryParams.departmentId = this.depts[0].id;
      // 设置默认选中
      this.$nextTick(() => {
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId);
      });
      // 获取员工列表
      this.getEmployeeList();
    },
    // 选中节点
    selectNode(node) {
      this.queryParams.departmentId = node.id; // 选中节点id
      this.queryParams.page = 1; // 当前页码
      this.getEmployeeList();
    },
    // 模糊搜索
    changeValue() {
      // 防抖
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.queryParams.page = 1;
        this.getEmployeeList();
      }, 500);
    },
    // 获取员工列表
    async getEmployeeList() {
      const res = await getEmployeeList(this.queryParams);
      this.employeeList = res.rows;
      this.total = res.total;
    },
    // 分页
    changePage(newPage) {
      this.queryParams.page = newPage;
      this.getEmployeeList();
      // 切换页码处理选中问题
      this.$refs.employeeTable.store.states.selection =
        this.selectUsers[this.queryParams.page] || [];
      this.$refs.employeeTable.store.updateSelectionByRowKey(); // 重新计算selection
      this.$refs.employeeTable.store.updateAllSelected(); // 计算全选
    },
    // 导出excel
    async exportEmployeeExcel() {
      try {
        const res = await exportEmployeeExcel();
        if (res instanceof Blob) {
          FileSaver.saveAs(res, "员工信息表.xlsx"); // 下载文件
        } else {
          console.error("返回的数据不是Blob对象", res);
        }
      } catch (error) {
        console.error("导出Excel失败", error);
        // 检查错误信息中是否包含status字段
        if (error.response && error.response.status) {
          console.error("接口返回状态码", error.response.status);
        }
      }
    },
    // 删除员工
    async confirmDel(id) {
      await deleteEmployee(id);
      if (this.employeeList.length === 1 && this.queryParams.page > 1)
        this.queryParams.page--;
      this.$message.success("删除成功");
      this.getEmployeeList();
    },
    // 点击角色弹窗
    async btnRole(id) {
      this.roleList = await getEnableRoleList();
      // 记录当前点击的id 因为后边 确定取消要存取给对应的用户
      this.currentUserId = id;
      const { roleIds } = await getEmployeeDetail(id);
      this.roleIds = roleIds;
      this.showRoleDialog = true; // 调整顺序
    },
    // 确定分配权限
    async btnRoleOK() {
      await assignRole({
        id: this.currentUserId,
        roleIds: this.roleIds,
      });
      this.$message.success("分配用户角色成功");
      this.showRoleDialog = false;
    },
    // 多选发生变化
    selectChange(selectRows) {
      // 去重
      this.selectUsers = {
        ...this.selectUsers,
        [this.queryParams.page]: selectRows,
      };
    },
    // 发送信息弹框
    sendMultiMessage() {
      if (!this.all_users.length) {
        return this.$message.warning("请先选择要群发的员工");
      }
      this.showMultiMessageDialog = true;
    },
    // 发送消息
    async btnSendMultiMessage() {
      if (!this.all_users.length) {
        return this.$message.warning("发送的用户不能为空");
      }
      if (!this.messageForm.content) {
        return this.$message.warning("消息内容不能为空");
      }
      await sendMessage({
        userIds: this.all_users.map((item) => item.id), // [{ id: 11 }]  //[1,2,3,4,4]
        ...this.messageForm, // type content
      });
      this.$message.success("群发消息成功");
      this.messageForm = {
        type: 1,
        content: "",
      };
      this.showMultiMessageDialog = false;
    },
    // 删除群发的用户
    delSendUser(item) {
      // item哪一页的？？？？
      // 删除selectUser中的数据
      // 页面上取消勾选
      Object.keys(this.selectUsers).forEach((key) => {
        const index = this.selectUsers[key].findIndex(
          (row) => row.id === item.id
        );
        if (index > -1) {
          this.selectUsers[key].splice(index, 1); // 删除存储的数据
          this.$refs.employeeTable.toggleRowSelection(item, false); // 页面上取消勾选
        }
      }); // [1,2,3,4,5...]
    },
    // 关闭弹窗
    btnCancelSend() {
      this.showMultiMessageDialog = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.select_users {
  display: flex;
  flex-wrap: wrap;
  padding: 10px 10px;
  border: 1px solid #ccc;
  border-radius: 10px;
  span {
    margin: 6px 5px;
  }
}
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin: 10px;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>